package com.base.system.base.db.specifications;

import cn.hutool.core.util.ObjectUtil;

import javax.persistence.criteria.*;

/**
 * 相等的写法
 */
public class EqualSpecification<T> extends AbstractSpecification<T> {

    private static final long serialVersionUID = 5009829679650640940L;
    private final String property;
    private final Object[] values;

    public EqualSpecification(String property, JoinType joinType, Object... values) {
        this.property = property;
        this.values = values;
        this.joinType = joinType;
    }

    @Override
    public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {
        From from = getFrom(property, root);
        String attr = getProperty(property);
        if (ObjectUtil.isEmpty(values)) return cb.isNull(from.get(attr));
        if (values.length == 1) return getPredicate(from, cb, values[0], attr);
        Predicate[] predicates = new Predicate[values.length];
        for (int i = 0; i < predicates.length; i++) predicates[i] = getPredicate(from, cb, values[i], attr);
        return cb.or(predicates);
    }

    private Predicate getPredicate(From from, CriteriaBuilder cb, Object value, String attr) {
        return ObjectUtil.isEmpty(value) ? cb.isNull(from.get(attr)) : cb.equal(from.get(attr), value);
    }
}
